package com.iot08.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot08.api.service.DevQQConfigService;
import com.iot08.api.service.DeviceService;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.api.utils.ZLOpensslSign;
import com.iot08.api.vo.request.WatchQQSignVO;
import com.iot08.common.entity.app.DevQQConfig;
import com.iot08.common.utils.HttpReq;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Description: 腾讯设备QQ 对接推送系统
 * @time: 2021/09/08 14:22
 * @author: weichao
 */
@RestController
@RequestMapping("getway")
@Slf4j
public class WatchQQTXPushReceiveController {

    @Resource
    private DevQQConfigService devQQConfigService;
    @Resource
    private KafkaService kafkaService;

    @Value("${TXHLQQ_ToolPath}")
    private String TXHLQQ_ToolPath;
    @Value("${TXHLQQ_GUIDAndLicenseldFolderPath}")
    private String TXHLQQ_GUIDAndLicenseldFolderPath;
    @Value("${TXHLQQ_JYWATCHKEY}")
    private String TXHLQQ_JYWATCHKEY;

    @Value("${TXHLQQ_APPID}")
    private String TXHLQQ_APPID;

    @Value("${TXHLQQ_APPKey}")
    private String TXHLQQ_APPKey;

    //当前API 使用的域名
    @Value("${domain}")
    private String domaim;



    /**
     * 腾讯设备QQ通过 认证code 获取 用户openid 和登录凭证 accesstoken
     *
     * @param paramsMap 请求参数集合
     * @time: 2021/09/6 18:30
     * @author: weichao
     * @version 1.0
     */
    @PostMapping("qq/watch/pushreceive")
    @ResponseBody
    public ResponseMap watchQQPushMsgReceive(@RequestBody Map<String,Object> paramsMap, HttpServletRequest request) {
        log.info("收到 腾讯后台推送的系统消息 :{} ", paramsMap);
        // 通过这个消息 获取 openid 判定是哪个设备, 然后进行指令下发
        String toOpenid = paramsMap.get("To").toString();
        DevQQConfig openidOB = devQQConfigService.findOne(new Query(Criteria.where("openid").is(toOpenid)));
        if(openidOB != null){
            String imei = openidOB.getId();
            JSONObject sendMsgOB = new JSONObject();
            sendMsgOB.put("type", 200);
            sendMsgOB.put("pushMsgData", JSONObject.toJSONString(paramsMap));
//            kafkaService.emitDeviceDemand(imei, 200, sendMsgOB);
            log.info("收到 腾讯后台推送的QQ消息 发送openid:{} 和对应的imei:{} sendMsgOB:{}", toOpenid, imei, sendMsgOB);
        }


        ResponseMap map = new ResponseMap();
        map.put("ActionStatus", "OK");
        map.put("ErrorInfo", "");
        map.put("ErrorCode", 0);
        return map;
    }
}
